package com.yonyou.gmcc.gateway.web.util;

import java.util.Enumeration;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.tomcat.util.http.MimeHeaders;

import com.yonyou.gmcc.gateway.web.consts.CommonConstants;
import com.yonyou.gmcc.gateway.web.entity.UserEntity;
import com.yonyou.gmcc.gateway.web.interceptor.AuthCheckInterceptor;
import com.yonyou.gmcc.gateway.web.jwt.JwtHelper;
import com.yonyou.gmcc.gateway.web.jwt.Md5Utils;

import io.jsonwebtoken.Claims;

public class TokenCheck {
	private static Logger logger=Logger.getLogger(AuthCheckInterceptor.class);
	
	public static boolean check(HttpServletRequest req,
			HttpServletResponse res){

		UserEntity user=null;
		try {
			user = CookieUtil.getHeadUserInfo(req);
		} catch (Exception e1) {
			logger.debug("getUserinfo exception:"+e1.getMessage());
			e1.printStackTrace();
		}
//		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//小写的mm表示的是分钟  
		if (user==null) {
			logger.debug("--TokenCheck,user==null,RESPONSE_NON_LOGIN");
			res.setStatus(CommonConstants.RESPONSE_NON_LOGIN);
			return false;
		}else if(user.getToken()==null)
		{
			logger.debug("--TokenCheck,RESPONSE_TIME_OUT");
			res.setStatus(CommonConstants.RESPONSE_TIME_OUT);
            return false;
		}else{
	        setUserIdToHeader(req,user.getUserId());
			//根据key从缓存中判断是否登录
	        //以下为更新客户端的token，防止30分钟过期导致客户不嫩使用系统
	        String token=JwtHelper.createJWT(user.getUserName(), user.getUserId(), "", "", "", 12*60);
	        res.addHeader(CommonConstants.CHAT_COOKIE_NAME, token);
		}
		return true;
	}
    
	private static void setUserIdToHeader(HttpServletRequest req,String userId){
        Object obj1=ReflectionUtils.getFieldValue(req, "request");
        Object obj2=ReflectionUtils.getFieldValue(obj1, "request");
        Object obj3=ReflectionUtils.getFieldValue(obj2, "request");
        Object obj4=ReflectionUtils.getFieldValue(obj3, "coyoteRequest");
        System.out.println(obj4.toString());
        org.apache.coyote.Request r=(org.apache.coyote.Request)obj4;
        MimeHeaders m=r.getMimeHeaders();
        m.addValue(CommonConstants.USER_HEADER_NAME).setString(userId);
	}

//	private static UserEntity getCookieUser(Claims claims){
//		UserEntity user=new UserEntity();
//		user.setUserId(JwtHelper.getUserId(claims));
//		user.setUserName(JwtHelper.getUserName(claims));
//		return user;
//	}
//	private static String getJwtToken(String userInfo){
//		//拼装jwtAccessToken  
//		String md5userInfo=Md5Utils.getMD5(userInfo);
//        String jwtToken = JwtHelper.createJWT(md5userInfo, "",  
//                "role", "clientid", "",  
//                60*30 );  //30分钟
//        return jwtToken;
//	}
//	private static String getCookie(HttpServletRequest req, HttpServletResponse response){
//		Cookie[] cookies = req.getCookies();//这样便可以获取一个cookie数组
//		if(cookies==null)
//			return "";
//		for(Cookie cookie : cookies){
//		    if(CommonConstants.CHAT_COOKIE_NAME.equals(cookie.getName()))
//		      return cookie.getValue(); // get the cookie value
//		}
//		return "";
//	}

//    private static String getHeader(HttpServletRequest request) {
//        Enumeration headerNames = request.getHeaderNames();
//        while (headerNames.hasMoreElements()) {
//            String key = (String) headerNames.nextElement();
//        	if(CommonConstants.CHAT_COOKIE_NAME.equals(key))
//            	return request.getHeader(key);
//        }
//        return "";
//      }
//	private static void writeCookie(HttpServletRequest req, HttpServletResponse response,
//			String userInfo){
//		String jwtToken=getJwtToken(userInfo);
//		response.setCharacterEncoding("GBK");
//		response.setContentType("text/html;charset=GBK");
//		Cookie cookie; 
//		cookie=new Cookie(CommonConstants.CHAT_COOKIE_NAME,jwtToken);//用户ID 
//		cookie.setMaxAge(60*60);//cookie时间 
//		cookie.setPath(req.getContextPath()); //根据个人的不用，在不同功能的路径下创建 
//		response.addCookie(cookie); 
//        logger.info("---------jwtToken="+jwtToken);
//	}
}
